import React, {useEffect, useState} from "react";
import {Button, Card, Space, Table} from "@douyinfe/semi-ui";
import { IconPlus, IconDelete, IconRefresh, IconEdit, IconCopy, IconSync, IconTerminal } from '@douyinfe/semi-icons';
import {ColumnProps} from "@douyinfe/semi-ui/lib/es/table";
import {httpGet, PageResult, Result} from "../../utils/http";
import {Error, Success} from "../../utils/message";
import {ServerAdd} from "./server-add";
import {ServerUpdate} from "./server-update";
import {ServerTerminal} from "./server-terminal";

interface ServerProp {
    id: number;
    title: string;
    host: string;
    brief: string;
    createTime: string;
}

interface ServerQueryProp {
    page: number;
    limit: number;
}

const messageMap = new Map<number, string>([
    [-1, ''],
    [0, '刷新成功'],
    [1, '加载成功']
])

export const ServerPage = () => {

    const columns: ColumnProps[] = [
        {
            title: '名称',
            dataIndex: 'title',
            align: 'center'
        },
        {
            title: '地址',
            align: 'center',
            dataIndex: 'host',
        },
        {
            title: '创建时间',
            align: 'center',
            dataIndex: 'createTime',
        },
        {
            title: '备注',
            align: 'center',
            dataIndex: 'brief',
        },
        {
            title: '操作',
            dataIndex: 'operate',
            align: 'center',
            width: 150,
            render: (text, record) => <Space>
                <Button size={'small'} icon={<IconEdit />} onClick={() => openUpdate(record.id)}/>
                <Button size={'small'} icon={<IconCopy />} onClick={() => serverCopy(record.id)} />
                <Button size={'small'} icon={<IconSync />} onClick={() => pingServer(record.id)}/>
                <Button size={'small'} theme='light' type='tertiary' icon={<IconTerminal />} onClick={() => openTerminal(record.id)}/>
                <Button size={'small'} type={'danger'} icon={<IconDelete />} onClick={() => serverDelete(record.id)} />
            </Space>,
        },
    ];

    const [total, setTotal] = useState<number>(1);

    const [datasource, setDatasource] = useState<ServerProp[]>([
        {
            id: 1,
            title: 'NUC-11',
            host: '192.168.31.188',
            brief: '本地服务器地址',
            createTime: '2020-02-02 05:13',
        },
        {
            id: 2,
            title: '阿里云',
            host: '192.168.31.188',
            brief: '阿里云服务器',
            createTime: '2020-02-02 05:13',
        },
        {
            id: 3,
            title: '本地',
            host: '127.0.0.1',
            brief: '本机服务器地址',
            createTime: '2020-02-02 05:13',
        },
    ]);

    const [deleteFlag, setDeleteFlag] = useState<boolean>(true);
    const [loading, setLoading] = useState<boolean>(false);
    const [addVisible, setAddVisible] = useState<boolean>(false);
    const [updateVisible, setUpdateVisible] = useState<boolean>(false);
    const [terminalVisible, setTerminalVisible] = useState<boolean>(false);
    const [currId, setCurrId] = useState<number | undefined>(undefined);

    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const [serverQuery, setServerQuery] = useState<ServerQueryProp>({page: 1, limit: 10});

    const serverCopy = (id: number) => {
        httpGet<Result<ServerProp | string>, any>('/server/copy', {id: id}).then(res => {
            if (res.code === 200) {
                setDatasource([...datasource, res.data as ServerProp]);
                Success('复制服务成功');
            } else {
                Error(res.data as string);
            }
        }).catch(err => {
            Error(err);
        })
    }

    const serverDelete = (id: number | string) => {
        httpGet<Result<ServerProp | string>, any>('/server/delete', {ids: id}).then(res => {
            if (res.code === 200) {
                loadData(serverQuery.page, serverQuery.limit, -1)
                Success('删除服务成功');
            } else {
                Error(res.data as string);
            }
        }).catch(err => {
            Error(err);
        })
    }

    const batchDelete = () => {
        if (selectedRowKeys.length <= 0) {
            Error("请先选择数据在执行删除")
        } else {
            serverDelete(selectedRowKeys.join(","))
        }
    }

    const loadData = (page: number, limit: number, isLoad: -1 | 0 | 1) => {
        setLoading(true);
        httpGet<PageResult<ServerProp>, any>('/server/list', {page: page, limit: limit}).then(res => {
            setLoading(false);
            if (res.code === 200) {
                if (isLoad !== -1) {
                    Success(messageMap.get(isLoad)!);
                }
                const {total, records} = res.data;
                setTotal(total);
                setDatasource(records);
            } else {
                Error(res.msg)
            }
        }).catch(err => {
            setLoading(false);
            Error(err);
        })
    }

    const closeModel = (isLoad: boolean, type: 'add' | 'update') => {
        if (type === 'add') {
            setAddVisible(false);
        }
        if (type === 'update') {
            setUpdateVisible(false);
            setCurrId(undefined);
        }
        if (isLoad) {
            loadData(serverQuery.page, serverQuery.limit, -1);
        }
    }

    const openUpdate = (id: number) => {
        setCurrId(id);
        setUpdateVisible(true);
    }

    const openTerminal = (id: number) => {
        setCurrId(id);
        setTerminalVisible(true);
    }

    const pingServer = (id: number) => {
        httpGet<Result<string>, any>('/server/test', {id: id}).then(res => {
            if (res.code === 200) {
                Success(res.data)
            } else {
                Error(res.data)
            }
        }).catch(err => {
            Error(err)
        })
    }

    useEffect(() => {
        setDeleteFlag(selectedRowKeys.length <= 0)
    }, [selectedRowKeys])

    useEffect(() => {
        loadData(serverQuery.page, serverQuery.limit, 1)
    }, [])


    return <Card shadows='always'>
        <Space style={{marginBottom: 18}}>
            <Button icon={<IconPlus />} onClick={() => setAddVisible(true)}>增加</Button>
            <Button icon={<IconRefresh />} onClick={() => loadData(serverQuery.page, serverQuery.limit, 0)}>刷新</Button>
            <Button type={'danger'} icon={<IconDelete />} disabled={deleteFlag} onClick={batchDelete}>删除</Button>
        </Space>
        <Table
            size={'small'}
            rowKey={'id'}
            bordered={true}
            columns={columns}
            loading={loading}
            rowSelection={{
                selectedRowKeys: selectedRowKeys,
                onChange: (selectedRowKeys?: (string | number)[], selectedRows?: ServerProp[]) => {
                    console.log('selectedRowKeys', selectedRowKeys, 'selectedRows', selectedRows);
                },
                onSelect: (record?: ServerProp, selected?: boolean, selectedRows?: ServerProp[], nativeEvent?: React.MouseEvent) => {
                    if (selected && record) {
                        setSelectedRowKeys([...selectedRowKeys, record.id])
                    } else {
                        setSelectedRowKeys([...selectedRowKeys.filter(item => item != record?.id)])
                    }
                },
                onSelectAll: (selected?: boolean, selectedRows?: ServerProp[], changedRows?: ServerProp[]) => {
                    if (selected && changedRows) {
                        let numbers: number[] = changedRows.map(item => item.id);
                        setSelectedRowKeys([...selectedRowKeys, ...numbers])
                    } else {
                        setSelectedRowKeys([])
                    }
                }
            }}
            pagination={{
                showQuickJumper: true,
                showTotal: true,
                total: total,
                pageSize: 10,
                onChange: (currentPage: number, pageSize: number) => {

                }
            }}
            dataSource={datasource} />
        {/* 增加服务 */}
        <ServerAdd visible={addVisible} closeModal={(isLoad) => closeModel(isLoad, 'add')} />
        {/* 更新服务 */}
        <ServerUpdate visible={updateVisible} id={currId!} closeModal={(isLoad) => closeModel(isLoad, 'update')} />
        {/* 打开WebSsh */}
        <ServerTerminal visible={terminalVisible} id={currId!} closeModel={() => setTerminalVisible(false)} />
    </Card>
}